<template>
  <section class="todoapp">
    <hm-header @add-event="add"></hm-header>
    <hm-main
      :list="newList"
      @check-event="checked"
      @changeAll-event="changeAll"
      @del-event="del"
    ></hm-main>
    <hm-footer
      :list="list"
      @clearAll-event="clearAll"
      @clickAll-status="status = $event"
      :status="status"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/active": "undone",
  "#/completed": "done",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 1, done: false, task: "睡觉" },
      //   { id: 2, done: true, task: "吃饭" },
      //   { id: 3, done: false, task: "打豆豆" },
      // ],
      list: JSON.parse(window.localStorage.getItem("list")) || [],
      status: obj[location.hash] || "all",
    };
  },
  methods: {
    checked(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.done = !obj.done;
    },
    changeAll(value) {
      this.list.forEach((item) => (item.done = value));
    },
    del(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    add(task) {
      if (task === "") {
        return alert("不能为空");
      }
      const id = this.list.slice(-1)[0].id + 1;
      const obj = {
        id,
        task,
        done: false,
      };
      this.list.push(obj);
    },
    clearAll() {
      // console.log("清除");
      this.list = this.list.filter((item) => item.done === false);
    },
  },
  computed: {
    newList() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "undone") {
        return this.list.filter((item) => item.done === false);
      } else {
        return this.list.filter((item) => item.done === true);
      }
    },
  },
  watch: {
    list: {
      // immediate: true,
      deep: true,
      handler(newValue) {
        window.localStorage.setItem("list", JSON.stringify(newValue));
      },
    },
  },
};
</script>

<style></style>
